import { defineStore } from 'pinia'
import { canvas } from '../canvas/canvasInstance'

export const useSimControllerStore = defineStore('simController', {
  state: () => ({
    simState: 'stopped' as 'idle' | 'running' | 'paused' | 'stopped',
    simTime: 0, //单位：秒
    startTime: 0, //单位：毫秒
    simSpeed: 1
  }),
  actions: {
    //切换仿真状态
    async toggleSimState(status: 'running' | 'paused' | 'stopped' | 'resume') {
      if (status === 'running') {
        //在仿真开始前，进行一些预处理
        await this.beforeSimRunning()

        if (this.simState === 'running') {
          return
        }
        //记录当前时间戳
        this.startTime = Date.now()
      }
      if (status !== 'resume') {
        this.simState = status
      } else {
        this.simState = 'running'
      }

      window.electron.ipcRenderer.send('simulationStatus', status)

      if (status === 'stopped') {
        //清除画布中的产品节点
        this.clearProductNode()
      }
    },

    //设置仿真速度
    setSimSpeed() {
      window.electron.ipcRenderer.send('simulationSpeed', this.simSpeed)
    },

    async beforeSimRunning() {
      //在仿真开始前，进行一些预处理
      //初始化交通网络
      await window.electron.ipcRenderer.invoke('handleTrafficNetwork', 'initTrafficNet', [])
    },

    //清除画布中的产品节点
    clearProductNode() {
      const productIds = canvas
        .getNodes()
        .filter((node) => node.shape === 'product-node')
        .map((node) => node.id)
      canvas.removeCells(productIds)
    }
  }
})
